﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess.Classes;
using DataAccess;
using System.IO;

public partial class Admin_EditProduct : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            PopulateControls();
    }
    private void PopulateControls()
    {
        // Lay danh sach Category dua vao DropDownList (DDL) 
        // Dat value cho DDL la truong CategoryID 
        ddlCategory.DataValueField = "CategoryID";
        // Dat phan hien thi (text) la truong Name 
        ddlCategory.DataTextField = "Name";
        ddlCategory.DataSource = Category.All();
        ddlCategory.DataBind();

        string cid = Request.QueryString["cid"] ?? "";
        // Neu co QueryString cid ==> cap nhat Product 
        if (cid != "")
        {
            // Lay Product theo gia tri cid 
            Product data = Product.Single(cid);
            // Khong ton tai Product nay trong he thong 

            // chuyen huong ve trang Product.aspx 
            if (data == null)
                Response.Redirect("~/Admin/Product.aspx");

            // Nguoc lai thi dua du lieu vao form de tien hanh cap nhap 
            // Dat ten trang web 
            lblTitle.Text = "Edit Product";

            // Luu lai gia tri ID cua Product hien dang cap nhat 
            lblId.Text = data.ProductID.ToString();

            // Gan cac thong tin con lai vao form 
            txtName.Text = data.Name;
            txtDes.Text = data.Description;
            txtPrice.Text = data.Price.HasValue ? data.Price.Value.ToString() : "";
            lblImage.Text = data.Image;
            lblThumnail.Text = data.Thumbnail;
            chkPromoFront.Checked = data.PromoFront.GetValueOrDefault(false);
            ddlCategory.SelectedValue = data.CategoryID.ToString();
            btnReset.Visible = false;
        }
        else
        {
            // Khong co QueryString cid ==> them moi Product 
            // Dat ten trang web 
            lblTitle.Text = "Add Product";

            // Hien nut reset (xoa trang form de nhap lai) 
            btnReset.Visible = true;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        // Them su kien cho nut Save 
        btnSave.Click += new EventHandler(btnSave_Click);
        btnUploadImage.Click += new EventHandler(btnUploadImage_Click);
        btnUploadThumbnail.Click += new EventHandler(btnUploadThumbnail_Click);
    }

    // co the cau hinh các file hop le o web.config 
    // sau do them phuong thuc o GlobalConfiguration.cs de lay gia tri do  
    bool CheckFileType(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        switch (ext.ToLower())
        {
            case ".gif":
                return true;
            case ".png":
                return true;
            case ".jpg":
                return true;
            case ".jpeg":
                return true;
            default:
                return false;
        }
    }

    // Ham upload chung dung cho ca 2 button upload 
    // fileupload: dang upload thumbnail hay image 
    // label: dung de hien thi ten hinh anh 
    void Upload(FileUpload fileupload, Label label)
    {
        try
        {
            // Kiem tra co file upload va kich thuoc file <= 500KB 
            if (fileupload.HasFile && fileupload.PostedFile.ContentLength <= 500000)
            {
                // Kiem tra loai file 
                if (CheckFileType(fileupload.FileName))
                {
                    // Lay duong dan tuong doi o server 
                    String filePath = "~/ProductImages/" + fileupload.FileName;
                    // Luu vao duong dan o tren 
                    // MapPath(filePath) ==> chuyen ve duong dan tuyet doi 
                    fileupload.SaveAs(MapPath(filePath));
                    label.Text = fileupload.FileName;
                    lblStatus.Text = "Upload successful";
                }
            }
            else
            {
                lblStatus.Text = "Uploading image failed";
            }
        }
        catch (Exception)
        {
            lblStatus.Text = "Uploading image failed";
        }
    }

    void btnUploadThumbnail_Click(object sender, EventArgs e)
    {
        Upload(fuThumbnail, lblThumnail);
    }

    void btnUploadImage_Click(object sender, EventArgs e)
    {
        // MapPath(filePath) 
        Upload(fuImage, lblImage);
    }

    // Lay du lieu tu form de them moi/cap nhat 
    private Product GetData()
    {
        Product data = null;
        if (lblId.Text != "")
            // lay thong tin cu tu Database de cap nhat 
            data = Product.Single(lblId.Text);
        else
            data = new Product(); // them moi 
        data.Name = txtName.Text;
        data.Description = txtDes.Text;
        if (txtPrice.Text != "")
            data.Price = Convert.ToDecimal(txtPrice.Text);
        data.Thumbnail = lblThumnail.Text;
        data.Image = lblImage.Text;
        data.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue);
        data.PromoFront = chkPromoFront.Checked;
        return data;
    }

    // Xoa trang form 
    private void ResetForm()
    {
        txtName.Text = "";
        txtDes.Text = "";
        txtPrice.Text = "";
        lblThumnail.Text = "";
        lblImage.Text = "";
        chkPromoFront.Checked = false;
        ddlCategory.SelectedValue = "0";
    }

    void btnSave_Click(object sender, EventArgs e)
    {
        // Neu tat ca du lieu deu duoc nhap hop le 
        if (Page.IsValid)
        {
            bool rs = false;
            // Lay du lieu tu form 
            Product data = GetData();

            // ID > 0 ==> Cap nhat va hien thong bao 
            if (data.ProductID > 0)
            {
                rs = Product.Update(data);
                lblStatus.Text = rs ? "Update successful" : "Update failed";
            }
            else
            {
                rs = Product.Add(data);
                lblStatus.Text = rs ? "Insert successful" : "Insert failed";

                // Neu them thanh cong thi xoa trang form de them tiep 
                if (rs)
                    ResetForm();
            }
        }
    }
}